#!/bin/bash
. lib.sh
FM_list="play_FM_list.txt"
string1="请输入数字选择播放(留空退出程序)："
string2="输入错误，请重新输入正确的数字！"
string3="没有输入任何数字，退出程序！"
string4="请输入存放音乐的目录(留空退出程序)："
string5="没有输入任何目录，退出程序！"
count=1
function mpv_install_debian {
	apt_install mpv
}
function mpv_install_termux {
	pkg_install mpv
}
function read_1 {
	read -p "$string1" number
}
function echo_1 {
	echo "$string2"
}
function echo_2 {
	echo "$string3"
}
function play {
	read -p "$string4" music_dir
	if [[ -z "$music_dir" ]];
	then
		echo "$string5"
		return 0
	else
		cd "$music_dir"
		$1
	fi
}
function order_play {
	mpv --ad=aac_fixed ./*
}
function random_play {
	mpv --shuffle --ad=aac_fixed ./*
}
function fm_mpv {
	while :; do
		mpv --ad=aac_fixed \
			--msg-level=ffmpeg=fatal \
			--loop-playlist=inf \
			--cache=yes \
			--network-timeout=60 \
			--idle=yes --keep-open=yes \
			"${FM_url[number]}"
		sleep 5
	done
	#mpv --cache=yes --cache-secs=120 --ad=aac_fixed "${FM_url[number]}"
}
function number_judge {
	if [[ -z "$number" ]]; then
		echo_2
		return 0
	elif ! [[ $number =~ ^[0-9]+$ ]]; then
		echo "请输入正确的数字!"
		return 1
	elif (( $number>=0 && $number<=$count )); then
		fm_mpv
		return 0
	else
		echo_1
		return 1
	fi
}
function play_FM {
	echo -e "\n\
FM列表：\n"
	mapfile -t array < "$FM_list"
	for i in "${!array[@]}"; do
		let order_number=$i+1
		FM_name[count]=$(echo "${array[$i]}" | cut -d "," -f 1)
		FM_url[count]=$(echo "${array[$i]}" | cut -d "," -f 2)
		echo "($order_number) ${FM_name[count]}"
		count=$(( $count + 1 ))
	done
	while true; do
		echo -e "\n"
		read_1
		number_judge
		if [[ $? -eq 0 ]]; then
			break
		fi
	done
}
function main {
	echo "菜单选项："
	echo -e "\n\
(1) 顺序播放\n\
(2) 随机播放\n\
(3) 播放网络FM\n"
	while true; do
		read_1
		if [[ -z $number ]]; then
			echo_2
			exit 0
		fi
		case $number in
			1)
				play order_play
				break
				;;
			2)
				play random_play
				break
				;;
			3)
				play_FM
				break
				;;
			*)
				echo_1
				;;
		esac
	done
}
judgment "mpv" mpv_install_termux mpv_install_debian
judgment_main "mpv"
